import Vue from 'vue';
import io from 'socket.io-client';
import Cookies from 'js-cookie';

const origin = 'wss://wss.lke.cloud.tencent.com';
let path = '/v1/qbot/chat/conn/';
let initSocket = 1;
const webIMSource = Vue.prototype.webIMSource;

let tokenArr = window.webimToken || [];
let mainToken = tokenArr.filter(item => {
    return item.type !== 4;
})[0].token;
console.log('mainToken', mainToken);


let socket = io(origin, {
    path: path,
    transports: ['websocket', 'polling'],
    withCredentials: true,
    auth: async (cb) => {
        try {
            if (initSocket === 1) {
                const token = mainToken || '';
                if (token) {
                    cb({ token: token });
                } else {
                    cb({ token: '' });
                }
                initSocket++;
            }
        } catch (e) {
            console.log('error', e);
            cb({ token: '' });
            Vue.prototype.$message.error('获取token失败');
        }
    }
}); // 建立连接

let systemEventEmit = (eventName, data) => {
    Vue.prototype.$eventHub.$emit(eventName, data);
};

// 监听
socket.on('connect', () => {
    const payload = JSON.stringify({
        from: 'webim',
        type: 'chat-connect',
    });
    window.parent.postMessage(payload, '*');
    // 监听连接是否成功
    systemEventEmit('connect');
});
socket.on('connect_error', () => {
    systemEventEmit('connectError');
    socket.connect();
});
socket.on('error', (error) => {
    systemEventEmit('error', error);
});
socket.on('disconnect', (reason) => {
    // 监听连接异常中断
    systemEventEmit('disconnect', reason);
});
socket.io.on('error', (error) => {
    systemEventEmit('SocketError', error);
});
socket.io.on('reconnect', (attemptNumber) => {
    systemEventEmit('reconnect', `Reconnected to server after ${attemptNumber} attempts`);
});
socket.io.on('reconnect_attempt', (attemptNumber) => {
    systemEventEmit('reconnectAttempt', `Attempt number ${attemptNumber} to reconnect to server`);
});
socket.io.on('reconnect_error', (error) => {
    systemEventEmit('reconnectError', error);
});
socket.io.on('reconnect_failed', () => {
    systemEventEmit('reconnectFailed');
});

let Socket = {
    emit(eventName, params) {
        params.search_network = window.webimToken[0].search_network
        let data = {
            payload: params
        };
        console.log('Socketemit', eventName, params);
        socket.emit(eventName, data);
    },
    on(eventName, cb) {
        let dataCB = (data) => {
            cb(data ? data.payload : data);
        };
        socket.on(eventName, dataCB);
    },
    disconnect(){
        socket.disconnect();
    },
    reconnect(data) {
        if(!mainBalance && data){
            mainBalance = data
            socket.connect();
        }
    }
};

Vue.prototype.$socket = Socket;

// 坐席右侧问答socket
// let subTokenArr = tokenArr.filter(item => {
//     return item.type === 4;
// });
// let subToken = subTokenArr[0] ? subTokenArr[0].token : '';

// console.log('subToken', subToken);



// WEBPACK FOOTER //
// ./src/manage/utils/Socket.js